package com.rednote.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.rednote.config.OssConfig;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Component
@Slf4j
public class OssUtil {
    @Resource
    private OssConfig ossConfig;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
    }

    public String uploadFile(MultipartFile file, String directory) {
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = directory + "/" + UUID.randomUUID().toString() + extension;

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectName,
                    file.getInputStream()
            );
            ossClient.putObject(putObjectRequest);
            System.out.println("文件上传成功，路径：" + ossConfig.getUrlPrefix() );
            return objectName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败");
        }
    }
    public String uploadFile(InputStream inputStream, String directory, String fileName) {
        String objectName = directory + "/" + fileName;

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectName,
                    inputStream
            );
            ossClient.putObject(putObjectRequest);
            return objectName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败");
        }
    }
    public void deleteFile(String objectName) {
        try {
            ossClient.deleteObject(ossConfig.getBucketName(), objectName);
        } catch (Exception e) {
            log.error("删除OSS文件失败", e);
            throw new RuntimeException("删除文件失败");
        }
    }

    /**
     * 从OSS下载文件并保存到项目根目录
     * @param objectName OSS中的文件路径（不包含bucket名称）
     * @param localFileName 保存到本地的文件名
     * @return 保存的文件路径
     */
    public String downloadFile(String objectName, String localFileName) {
        OSSObject ossObject = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        
        try {
            // 获取OSS文件对象
            ossObject = ossClient.getObject(ossConfig.getBucketName(), objectName);
            inputStream = ossObject.getObjectContent();
            
            // 创建本地文件
            File localFile = new File(localFileName);
            fileOutputStream = new FileOutputStream(localFile);
            
            // 读取OSS文件内容并写入本地文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            
            log.info("文件下载成功，保存路径: {}", localFile.getAbsolutePath());
            return localFile.getAbsolutePath();
            
        } catch (Exception e) {
            log.error("文件下载失败", e);
            throw new RuntimeException("文件下载失败: " + e.getMessage());
        } finally {
            // 关闭资源
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (ossObject != null) {
                    ossObject.close();
                }
            } catch (IOException e) {
                log.error("关闭资源失败", e);
            }
        }
    }

    /**
     * 测试方法：下载并读取文本文件内容
     * @param objectName OSS中的文件路径
     */
    public void testDownloadAndReadText(String objectName) {
        OSSObject ossObject = null;
        BufferedReader reader = null;
        
        try {
            // 获取OSS文件对象
            ossObject = ossClient.getObject(ossConfig.getBucketName(), objectName);
            reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            
            // 读取并打印文件内容
            String line;
            log.info("文件内容：");
            while ((line = reader.readLine()) != null) {
                log.info(line);
            }
            
        } catch (Exception e) {
            log.error("读取文件内容失败", e);
            throw new RuntimeException("读取文件内容失败: " + e.getMessage());
        } finally {
            // 关闭资源
            try {
                if (reader != null) {
                    reader.close();
                }
                if (ossObject != null) {
                    ossObject.close();
                }
            } catch (IOException e) {
                log.error("关闭资源失败", e);
            }
        }
    }
}